package com.redstar.interesting.common.starter.redis;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;

import java.io.Serializable;

@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfigurer implements InitializingBean {

    private final Logger log = LoggerFactory.getLogger(RedisConfigurer.class);

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private String port;
    @Value("${spring.redis.username}")
    private String username;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.database}")
    private String database;

    private RedissonClient redissonClient;

    @Autowired
    private LettuceConnectionFactory lettuceConnectionFactory;

    private RedisTemplate<String, Serializable> jdkRedisTemplate;

    @Override
    public void afterPropertiesSet() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://" + host + ":" + port)
                .setPassword(StringUtils.isEmpty(password) ? null : password);
        redissonClient = Redisson.create(config);
        log.info("redis链接成功,redisson创建成功...... host:{},database:{}", host, database);
    }

    @Bean(name = "jdkRedisTemplate", autowire = Autowire.BY_NAME)
    @ConditionalOnMissingBean
    public RedisTemplate jdkRedisTemplate() {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        return redisTemplate;
    }


    @Bean(name = "redissonClient", autowire = Autowire.BY_NAME)
    public RedissonClient redissonClient(){
        return redissonClient;
    }

}
